--[[
文件名: run_reactor.lua
描述: 运行流体反应堆
作者: 671643387@qq.com
创建日期: 2025-09-20
]]

local thread = require("thread")
local serialization = require("serialization")
local oc_util = require('kernel.util.oc_util')
local term_util = require('kernel.util.term_util')
local FluidReactor = require('fluid_reactor.fluid_reactor')

local run_reactor = function(filename)
    -- 读取配置文件
    local content = oc_util.read_file(filename)
    if not content then
        print('Read config file failed')
        return
    end
    -- 创建一个反应堆结构
    local reactor = FluidReactor:new()
    -- 按照配置初始化反应堆
    local config = serialization.unserialize(content)
    if not (config and reactor:load_config(config)) then
        print('Invalid config file')
        return false;
    end
    -- 反应堆初始化成功
    print('Reactor initialized')
    reactor:dump()
    -- 运行反应堆
    local running = true
    local runner = thread.create(function()
        while running do
            reactor:tick()
            os.sleep()
        end
    end)
    -- 等待退出
    while true do
        print("press q to exit")
        local str = term_util.read_str()
        if str == 'q' then
            running = false
            reactor:shutdown()
            thread.waitForAll({ runner })
            break
        end
    end
end

return run_reactor
